import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class SnakeHead extends GameObj {
    private String direction = "right";

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public SnakeHead(int x, int y, Image img, GameFrame frame) {
        super(x, y, img, frame);
        this.frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
               changDirection(e);
            }
        });
    }
//键盘控制蛇方向
    public void changDirection(KeyEvent keyEvent){
    switch (keyEvent.getKeyCode()){
        case KeyEvent.VK_W:
            direction = "up";
            img = GameUtils.upImg;
            break;
        case KeyEvent.VK_S:
            direction = "down";
            img = GameUtils.downImg;
            break;
        case KeyEvent.VK_D:
            direction = "right";
            img = GameUtils.rightImg;
            break;
        case KeyEvent.VK_A:
            direction = "left";
            img = GameUtils.lefttImg;
            break;
    }
    }
    public void move() {
        ArrayList<SnakeBody> snakeBody = this.frame.snakeBody;
        for (int i = snakeBody.size()-1;i>=0;i--){
            if (i==0){//蛇的第一节
                snakeBody.get(i).x = this.x;
                snakeBody.get(i).y = this.y;
            }
            else {
                //蛇身的碰撞，咬到自己
                if (this.x == snakeBody.get(i).x&& this.y ==snakeBody.get(i).y){
                    GameFrame.state = 3;
                }
                snakeBody.get(i).x = snakeBody.get(i-1).x;
                snakeBody.get(i).y = snakeBody.get(i-1).y;
            }
        }
        switch (direction) {
            case "right":
                x += frame.step;
                x = x > frame.frameHeight - frame.step ? 0 : x;
                break;
            case "left":
                x -= frame.step;
                x = x < 0 ? frame.frameHeight - frame.step : x;
                break;
            case "up":
                y -= frame.step;
                y = y < 0 ? frame.frameHeight - frame.step : y;
                break;
            case "down":
                y += frame.step;
                y = y > frame.frameHeight - frame.step ? frame.step : y;
                break;

        }
    }

    @Override
    public void paintSelf(Graphics graphics) {
        super.paintSelf(graphics);
        //蛇吃到食物
        if (this.frame.foodObj.x ==this.x&& this.frame.foodObj.y == this.y){
            //产生新的食物
            this.frame.foodObj = this.frame.getRandomFood();
            //蛇身增长
            this.frame.snakeBody.add(new SnakeBody(0,0,GameUtils.bodyImg,this.frame));

        }
        move();
    }
}
